<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

use \think\Request;

/*********************************************加密解密部分*********************************************/

/**
 * 添加填充数据,PKCS7规则
 *
 * @param $source
 * @return string
 */
function add_pkcs7_padding($source)
{
    //去除额外代码
    $source = trim($source);

    //计算块大小
    $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);

    //数据填充
    $pad = $block - (strlen($source) % $block);
    if ($pad <= $block) {
        $clientar = chr($pad);
        $source .= str_repeat($clientar, $pad);
    }
    return $source;
}

/**
 * AES加密
 *
 * @param string $key 加密key值
 * @param string $plaintext 明文
 * @return string 密文
 */
function aes_encrypt($key, $plaintext)
{
    //通过key截取vector
    $vector = substr($key, 0, 16);

    //进行数据填充
    $plaintext = add_pkcs7_padding($plaintext);

    //加密数据
    $ciphertext =  mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key,
        $plaintext, MCRYPT_MODE_CBC, $vector);

    //返回base64编码后的密文
    return base64_encode($ciphertext);
}


/**
 * 移去填充算法
 * @param string $source
 * @return string
 */
function remove_pkcs7_padding($source)
{
    $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $clientar = substr($source, -1, 1);
    $num = ord($clientar);
    if($num > $block)
    {
        return $source;
    }
    $len = strlen($source);
    for($i = $len - 1; $i >= $len - $num; $i--)
    {
        if(ord(substr($source, $i, 1)) != $num)
        {
            return $source;
        }
    }
    $source = substr($source, 0, -$num);
    return $source;
}

/**
 * 解密方法
 * @param string $str
 * @return string
 */
function aes_decrypt($key, $ciphertext)
{
    //AES, 128 ECB模式加密数据
    $ciphertext = base64_decode($ciphertext);

    //获取vector
    $vector = substr($key, 0, 16);
    $plaintext =  mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $ciphertext, MCRYPT_MODE_CBC, $vector);

    return remove_pkcs7_padding($plaintext);

}

/**
 * 检测URL是否正确
 *
 * @param String $url 待检测URL
 * @return bool
 */
function check_url($url)
{
    $client = curl_init();
    curl_setopt ($client, CURLOPT_URL, $url);
    //不下载
    curl_setopt($client, CURLOPT_NOBODY, 1);
    //设置超时
    curl_setopt ($client, CURLOPT_CONNECTTIMEOUT, 3);
    curl_setopt($client, CURLOPT_TIMEOUT, 3);
    curl_exec($client);
    $http_code = curl_getinfo($client, CURLINFO_HTTP_CODE);
    if($http_code == 200)
    {
        return true;
    }
    return false;
}

/**
 * 判断是否为web图片
 *
 * @param string $image 图片地址
 * @return bool 如果是web图片，返回true；否则返回false
 */
function check_web_image($image)
{
    //检测是否为链接
    if (!check_url($image))
    {
        return false;
    }

    //获取headers信息
    $headers = get_headers($image, 1);

    //获取内容类型
    $contentType = $headers["Content-Type"];

    //根据Content-Type判断是否为图片
    if (strpos($contentType, "image/") === 0)
    {
        return true;
    }

    return false;
}


/**
 * 当前日期时间
 *
 * @return false|string
 */
function now_datetime()
{
    return time();
}

/**
 *时间戳显示为日期
 */
function show_datetime($time){
    return empty($time) ? '' : date('Y-m-d H:i:s',$time);
}

/*************************************************发送消息****************************************/

/**
 * 发送API错误
 *
 * @param string $code 编码
 * @param string $error 错误内容
 */
function send_api_error($code, $error)
{
    $arr = array("result_code" => $code, "result_info" => $error);

    if (!input('?get.no_encrypt'))
    {
        $body = aes_encrypt(config("aes_encrypt_key"), json_encode($arr, JSON_UNESCAPED_UNICODE));
        die(json_encode(['body'=>$body],JSON_UNESCAPED_UNICODE));
    }
    else
    {
        die(json_encode($arr, JSON_UNESCAPED_UNICODE));
    }
}

/*****************************错误编码****************************/
//登录异常错误
define("H_API_ERROR_TOKEN", "1111");
//用户输入错误
define("H_API_ERROR_USER", "2222");
//APP开发者错误
define("H_API_ERROR_DEVELOPER", "3333");
//服务器端开发者错误
define("H_API_ERROR_SERVER", "4444");


/**
 * 发送服务器级别信息
 *
 * @param string $error 错误信息
 */
function send_server_error($error = "")
{
    send_api_error(H_API_ERROR_SERVER, $error);
}

/**
 * 发送开发者级别错误信息
 *
 * @param string $error 错误信息
 */
function send_developer_error($error = "")
{
    send_api_error(H_API_ERROR_DEVELOPER, $error);
}

/**
 * 发送用户输入错误
 *
 * @param string $error
 */
function send_user_error($error = "")
{
    send_api_error(H_API_ERROR_USER, $error);
}

/**
 * 发送登录异常
 *
 * @param string $error
 */
function send_token_error($error = "")
{
    send_api_error(H_API_ERROR_TOKEN, $error);
}

/**
 * 验证银行卡号是否有效(前提为16位或19位数字组合)
 *
 * @param string $card 银行卡号
 * @return bool                         有效返回true,否则返回false
 */
function validate_bank_card($card)
{
    //第一步,反转银行卡号
    $cardNum = strrev($card);

    //第二步,计算各位数字之和
    $sum = 0;
    for ($i = 0; $i < strlen($cardNum); ++$i)
    {
        $item = substr($cardNum, $i, 1);
        //
        if ($i % 2 == 0)
        {
            $sum += $item;
        }
        else
        {
            $item *= 2;
            $item = $item > 9 ? $item - 9 : $item;
            $sum += $item;
        }
    }

    //第三步,判断数字之和余数是否为0
    if ($sum % 10 == 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

/**
 * 验证身份证号是否合法
 *
 * @param string $identity 待验证的身份证号
 * @return bool
 */
function validate_identity($identity)
{
    //判断证号位数
    if (!preg_match("/(\\d{18})|(\\d{17}(\\d|X|x))/i", $identity))
    {
        return false;
    }

    //每位数对应的乘数因子
    $factors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];

    //计算身份证号前17位的和
    $sum = 0;
    for ($index = 0; $index < 17; ++$index)
    {
        $sum += $factors[$index] * intval(substr($identity, $index, 1));
    }

    //将和对11取余
    $mod = $sum % 11;
    //最后一位字符
    $lastLetter = substr($identity, -1, 1);

    //根据获得的余数，获取验证码
    switch ($mod)
    {
        case 0:
            return $lastLetter == 1;
        case 1:
            return $lastLetter == 0;
        case 2:
            return strtoupper($lastLetter) == "X";
        default:
            return $lastLetter == 12 -$mod;
    }
}

/**
 * 文件上传保存名称
 *
 * @return string 文件上传后的名称
 */
function upload_save_name()
{
    return date("m/d/Y") . '/' . md5(microtime(true));
}



/**
 * 获取指定分类的完整名称
 *
 * @param $id
 * @return mixed
 */
function get_category_whole_name($id)
{
    return db("category")
        ->where("id", $id)
        ->value("title");
}

/*获取指定的apply的用户名*/
function getapplyinfo($appid){
  $appinfo = db('apply')->where("id='".$appid."'")->value('uid');
  if(empty($appinfo)){
    return '';
  }
  $username = db('user')->where("id='".$appinfo."'")->value('username');
  if(empty($username)){
    return '';
  }
  return "已指定给:".$username;
}

/**
 * 生成指定长度的随机数
 * @param $length
 * @param bool $numeric
 * @return string
 */
function random($length, $numeric = false)
{
    $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
    $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
    if ($numeric) {
        $hash = '';
    } else {
        $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
        $length--;
    }
    $max = strlen($seed) - 1;
    for ($i = 0; $i < $length; $i++) {
        $hash .= $seed{mt_rand(0, $max)};
    }
    $hash=strtoupper($hash);
    return $hash;
}



/**
 * 生成APP URL
 *
 * @param $url
 * @return mixed|string
 */
function generate_app_url($url)
{
    //拼接完整URL
    $url = request()->domain() . $url;

    //使用HTTP替换HTTPS
    $url = str_replace("https://", "http://", $url);

    //将api或admin替换为app
    $url = str_replace("api.", "app.", $url);
    $url = str_replace("admin.", "app.", $url);

    return $url;
}

/**
 * 判断请求是否为IOS系统
 *
 * @return bool
 */
function is_ios()
{
    // 获取设备代理信息
    $agent = request()->header('USER_AGENT');

    // 判断是否有IOS信息
    if (strpos($agent, 'iPhone') || strpos($agent, 'iPad'))
    {
        return true;
    }

    return false;
}



function get_regionName($rid){
    $cname = db('region')->where('id',$rid)->value('title');
    return empty($cname) ? '' : $cname;
}



function save_money_log($uid,$union_id='',$type,$money,$source){
    $data = [
        'uid'=>$uid,
        'union_id'=>$union_id,
        'type'=>$type,
        'money'=>$money,
        'source'=>$source,
        'create_time'=>now_datetime()
    ];
    db('money_log')->insert($data);
}

/**
 * 删除路径
 *
 * @param $directory
 * @return bool
 */
function removeDirectory($directory)
{
    //如果目录不存在，则返回上级操作
    if (!file_exists($directory))
    {
        return false;
    }

    //如果是文件或文件链接则删除文件
    if (is_file($directory) || is_link($directory))
    {
        return unlink($directory);
    }

    //如果是路径，则递归处理
    $dir = dir($directory);
    if($dir)
    {
        //递归处理文件
        while (false !== $entry = $dir->read())
        {
            if ($entry == '.' || $entry == '..')
            {
                continue;
            }

            //递归
            removeDirectory($directory . '/' . $entry);
        }
    }

    //关闭文件
    $dir->close();

    //删除路径
    return rmdir($directory);
}
/**
 * 清除缓存
 */
function clear_cache()
{
    //清除临时文件
    {
        $dirs = array(TEMP_PATH);
        foreach($dirs as $value)
        {
            removeDirectory($value);
        }
    }

    //清除缓存文件
    {
        $dirs = array(CACHE_PATH);
        foreach($dirs as $value)
        {
            removeDirectory($value);
        }
    }
}



/**
 * 验证手机号是否正确
 *
 * @param string $mobile                       待验证的手机号
 * @return int                          如果正确则返回true
 */
function verify_mobile($mobile)
{
    $reg = config('tel_regular');

    return preg_match($reg, $mobile) ? true : false;
}

/**
 *  验证邮箱是否正确
 *
 * @param $email
 * @return int
 */
function verify_email($email)
{
    if (!$email) {
        return false;
    }

    return preg_match('#[a-z0-9&\-_.]+@[\w\-_]+([\w\-.]+)?\.[\w\-]+#is', $email) ? true : false;
}

function curl_post($url,$array){

    $curl = curl_init();
    //设置提交的url
    curl_setopt($curl, CURLOPT_URL, $url);
    //设置头文件的信息作为数据流输出
    curl_setopt($curl, CURLOPT_HEADER, 0);
    //设置获取的信息以文件流的形式返回，而不是直接输出。
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    //设置post方式提交
    curl_setopt($curl, CURLOPT_POST, 1);
    //设置post数据
    $post_data = $array;
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
    if(!is_array($array))
    {
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER,array('Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($array)));
    }
    //执行命令
    $data = curl_exec($curl);
    //关闭URL请求
    curl_close($curl);
    //获得数据并返回
    return $data;
}

/*
*curl访问
*/
function https_request($url){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}

/**
 * 友好时间显示
 * @param $time
 * @return bool|string
 */
function friend_date($time)
{
    if (!$time)
        return false;
    $fdate = '';
    $d = time() - intval($time);
    $ld = $time - mktime(0, 0, 0, 0, 0, date('Y')); //得出年
    $md = $time - mktime(0, 0, 0, date('m'), 0, date('Y')); //得出月
    $byd = $time - mktime(0, 0, 0, date('m'), date('d') - 2, date('Y')); //前天
    $yd = $time - mktime(0, 0, 0, date('m'), date('d') - 1, date('Y')); //昨天
    $dd = $time - mktime(0, 0, 0, date('m'), date('d'), date('Y')); //今天
    $td = $time - mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')); //明天
    $atd = $time - mktime(0, 0, 0, date('m'), date('d') + 2, date('Y')); //后天
    if ($d == 0) {
        $fdate = '刚刚';
    } else {
        switch ($d) {
            case $d < $atd:
                $fdate = date('Y/m/d/', $time);
                break;
            case $d < $td:
                $fdate = '后天' . date('H:i', $time);
                break;
            case $d < 0:
                $fdate = '明天' . date('H:i', $time);
                break;
            case $d < 60:
                $fdate = $d . '秒前';
                break;
            case $d < 3600:
                $fdate = floor($d / 60) . '分钟前';
                break;
            case $d < $dd:
                $fdate = floor($d / 3600) . '小时前';
                break;
            case $d < $yd:
                $fdate = '昨天' . date('H:i', $time);
                break;
            case $d < $byd:
                $fdate = '前天' . date('H:i', $time);
                break;
            case $d < $md:
                $fdate = date('m/d H:i', $time);
                break;
            case $d < $ld:
                $fdate = date('Y/m/d', $time);
                break;
            default:
                $fdate = date('Y/m/d', $time);
                break;
        }
    }
    return $fdate;
}

/**
 *将时间戳 改为 今天 某月某日 星期几 这种
 * @param string $time 时间戳
 **/
function newsTime($time){
    $today_time = strtotime(date('Y-m-d'));
    $date_time = strtotime(date('Y-m-d',$time));
    $cha = $today_time-$date_time;
    $week = array("日","一","二","三","四","五","六");
    $begin_year = strtotime(date("Y",time())."-1"."-1"); //本年开始
    $cha2 = $today_time - $begin_year;
    if($cha==0){
        $date = '今天 '.date('m月d日',$time).' 星期'.$week[date('w',$time)];
    }elseif($cha > 0 && $cha <= 86400){
        $date = '昨天 '.date('m月d日',$time).' 星期'.$week[date('w',$time)];
    }elseif($cha > $cha2){
        $date = date('Y年m月d日',$time).' 星期'.$week[date('w',$time)];
    }else{
        $date = date('m月d日',$time).' 星期'.$week[date('w',$time)];
    }

    return $date;
}

/**
 *将时间戳 改为 倒计时
 * @param string $time 时间戳
 **/
function timeCountDown($time){
    $now = time();
    $cha = $time-$now;
    if($cha <= 0){
        $cha = 0;
    }
    return $cha;
    //下面暂时弃用
//    if($cha<=0){
//        $date = 'OO:OO:00';
//    }else{
//        $hour = intval($cha/3600);
//        $hour_second = $hour*3600;
//        $cha2 = $cha-$hour_second;
//        $minute = intval($cha2/60);
//        $minute_second = $minute*60;
//        $second = $cha-$hour_second-$minute_second;
//        if($hour<10){
//            $hour = '0'.$hour;
//        }
//        if($minute<10){
//            $minute = '0'.$minute;
//        }
//        if($second<10){
//            $second = '0'.$second;
//        }
//        $date = $hour.':'.$minute.':'.$second;
//    }
//    return $date;
}

/**
 * 时间戳转精确到分时间
 * @param $time
 * @return false|string
 */
function accurateDate($time){
    return date('Y/m/d H:i',$time);
}

function downloadFile($file_url,$new_name=''){
    if(!isset($file_url)||trim($file_url)==''){
        return [
            'status'=>1,
            'info'=>'文件地址不能为空'
        ];
    }
    if(!file_exists($file_url)){ //检查文件是否存在
        return [
            'status'=>1,
            'info'=>'文件不存在'
        ];
    }
    $file_name=basename($file_url);
    $file_type=explode('.',$file_url);
    $file_type=$file_type[count($file_type)-1];
    $file_name=trim($new_name=='')?$file_name:urlencode($new_name).'.'.$file_type;
    $file_content=fopen($file_url,'r'); //打开文件
    //输入文件标签
    header("Content-type: application/octet-stream");
    header("Accept-Ranges: bytes");
    header("Accept-Length: ".filesize($file_url));
    header("Content-Disposition: attachment; filename=".$file_name);
    //输出文件内容
    echo fread($file_content,filesize($file_url));
    fclose($file_content);
}

function show_star($mobile){
    return substr_replace($mobile,'*******',2,7);
}

function cut_star($str){
    $start = mb_substr($str,0,1,'utf-8');
    $end = mb_substr($str,-1,1,'utf-8');
    return $start.'******'.$end;
}

//用户密码加密方式
function encrypt_user_password($str){
    return md5(md5($str));
}


/**
* 验证身份证号是否合法
*
* @param string $identity 待验证的身份证号
* @return bool
*/
function validate_ind($identity){
  //判断证号位数
  if (!preg_match("/(\\d{18})|(\\d{17}(\\d|X|x))/i", $identity))
  {
      return false;
  }

  //每位数对应的乘数因子
  $factors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];

  //计算身份证号前17位的和
  $sum = 0;
  for ($index = 0; $index < 17; ++$index)
  {
      $sum += $factors[$index] * intval(substr($identity, $index, 1));
  }

  //将和对11取余
  $mod = $sum % 11;
  //最后一位字符
  $lastLetter = substr($identity, -1, 1);

  //根据获得的余数，获取验证码
  switch ($mod)
  {
      case 0:
          return $lastLetter == 1;
      case 1:
          return $lastLetter == 0;
      case 2:
          return strtoupper($lastLetter) == "X";
      default:
          return $lastLetter == 12 -$mod;
  }
}




//删除字符串中html注入
function remove_all_tags($str){
    $str = str_replace(PHP_EOL, '', $str);
    $str = str_replace(array("\r\n", "\r", "\n"), "", $str);
    $str = str_replace(' ','',$str);
    $str = str_replace("'","‘",$str);
    $str = str_replace('"','”',$str);
    $str = htmlspecialchars($str);
    return $str;
}

//删除字符串中html注入
function remove_all_tags2($str){
    $str = str_replace("'","‘",$str);
    $str = str_replace('"','”',$str);
    $str = htmlspecialchars($str);
    return $str;
}

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
function get_client_ip($type = 0,$adv=false) {
    $type       =  $type ? 1 : 0;
    static $ip  =   NULL;
    if ($ip !== NULL) return $ip[$type];
    if($adv){
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos    =   array_search('unknown',$arr);
            if(false !== $pos) unset($arr[$pos]);
            $ip     =   trim($arr[0]);
        }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip     =   $_SERVER['HTTP_CLIENT_IP'];
        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip     =   $_SERVER['REMOTE_ADDR'];
        }
    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip     =   $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u",ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/*
 * 当前域名替换为home
 * */
function get_domain(){
    $domain = $_SERVER['HTTP_HOST'];
    $domain = str_replace('api','home',$domain);
    $domain = str_replace('admin','home',$domain);
    $domain = str_replace('business','home',$domain);
    return 'http://'.$domain;
}
/**
 * @return string
 */
function get_def_avatar(){
    return get_domain().'/static/default_avatar.png';
}
/*
 * 默认图片
 *
 * */
function default_img($url)
{
    if(empty($url))
    {
        $url="http://img.shangjiyin.com/alsdlalsdf.jpg";
    }
    return $url;
}

/**
 * 获取完整的图像地址
 *
 * @param string $image 图片地址
 * @return string
 */
function get_whole_image($image)
{
    if (empty($image) || check_web_image($image))
    {
        return $image;
    }
    else
    {
        return get_domain() . $image;
    }
}

//邀请注册链接
function get_regis_url($user){
    $url = get_domain().'/home/Index/register?telephone='.base64_encode($user['mobile']);
    return $url;
}

//昨天开始
function getBeginYesterday(){
    return mktime(0,0,0,date('m'),date('d')-1,date('Y'));
}
//昨天结束
function getEndYesterday(){
    return mktime(0,0,0,date('m'),date('d'),date('Y'))-1;
}
//今天开始
function getBeginToday(){
    return mktime(0,0,0,date('m'),date('d'),date('Y'));
}
//今天结束
function getEndToday(){
    return mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
}
//本周开始
function getBeginWeek(){
    $w = date('w');
    if(empty($w))$w=7;
    return mktime(0,0,0,date('m'),date('d')-$w+1,date('Y'));
}
//本周结束
function getEndWeek(){
    $w = date('w');
    if(empty($w))$w=7;
    return mktime(23,59,59,date('m'),date('d')-$w+7,date('Y'));
}
//本月开始
function getBeginMonth(){
    return mktime(0,0,0,date('m'),1,date('Y'));
}
//本月结束
function getEndMonth(){
    return mktime(23,59,59,date('m'),date('t'),date('Y'));
}
//本年开始
function getBeginYear(){
    return mktime(0,0,0,1,1,date('Y'));
}
//本年结束
function getEndYear(){
    return mktime(23,59,59,12,31,date('Y'));
}

function get_agent_level($id){
    if(empty($id)){
        return '无级别';
    }
    $title = db('agent_level')->where('id',$id)->value('title');
    return empty($title) ? '级别已删' : $title;
}

/**
 * 顺着parent_id往上找第一个代理
 * @param $id
 * @return array
 */
function get_agent($id){
    if(empty($id)){
        return ['status'=>0];
    }
    $user = db('user')->where('id',$id)->find();
    if(!$user){
        return ['status'=>0];
    }
    if($user['identity']==3){
        return ['status'=>1,'user'=>$user];
    }else{
        return get_agent($user['parent_id']);
    }
}

/**
 * 顺着parent_id往上找第一个城市合伙人
 * @param $id
 * @return array
 */
function get_partner($id){
    if(empty($id)){
        return ['status'=>0];
    }
    $user = db('user')->where('id',$id)->find();
    if(!$user){
        return ['status'=>0];
    }
    if($user['identity']==4){
        return ['status'=>1,'user'=>$user];
    }else{
        return get_partner($user['parent_id']);
    }
}

// 过滤掉emoji表情
function filterEmoji($str)
{
    $str = preg_replace_callback( '/./u',
        function (array $match) {
            return strlen($match[0]) >= 4 ? '' : $match[0];
        },
        $str);
    return $str;
}

/**
 * 判断访问接口的是安卓还是ios
 * @return string
 */
function get_device_type()
{
    //全部变成小写字母
    $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
    $type = '0';
    //分别进行判断
    if(strpos($agent, 'iphone') || strpos($agent, 'ipad'))
    {
        $type = '2';
    }

    if(strpos($agent, 'android'))
    {
        $type = '1';
    }
    return $type;
}

//生肖鼠相关

/*查看接收会员的用户名*/
function get_uname($uid){
	if($uid=='99999'){
		return '客服';
	}
	$uname = db('user')->where("id='".$uid."'")->field('username')->find();
	return empty($uname)?'未填写':$uname['username'];
}

/*查看接收会员的用户名*/
function get_telcode($uid){
    if($uid=='99999'){
        return '未知';
    }
    $uname = db('user')->where("id='".$uid."'")->field('selfphone')->find();
    return empty($uname)?'未填写':$uname['selfphone'];
}


/*查看当前会员可售订单为多少*/
function usercansale($uid){
	$sumprice = db(config("db_order_table"))->where("buyuid='".$uid."' and peiduistatus=1")->sum('basicprice');
	return empty($sumprice)?'0.00':$sumprice;
}


/*查看接收会员的真实姓名*/
function get_realname($uid){
	$uname =  db('user')->where("id='".$uid."'")->field('realname')->find();
	return empty($uname)?'未填写':$uname['realname'];
}

/*删减团队人数*/
function del_team($username){
	$userinfo = db('user')->where("username='".$username."'")->field('id,recommend')->find();
	if(empty($userinfo['id'])){
		return '';
	}else{
		/*先给本人团队人数加1，再传给上一级*/
		db('user')->where("username='".$username."'")->setDec('team_count');
		if(!empty($userinfo['recommend'])){
			del_team($userinfo['recommend']);
		}
	}
}

/*把pidstr转换成所有的上级id*/
function trans_pidstr($str){
    $str = explode(',',$str);
    $new_ary = [];
    foreach($str as $v){
        if(!empty($v)){
            $new_ary[] = $v;
        }
    }
    return $new_ary;
}

/*获取上级的所有合理的uid*/
function excommend($str){
    $str = explode(',',$str);
    $uidary = [];
    foreach($str as $v){
        if(!empty($v) && $v>0){
            $uidary[] = $v;
        }
    }
    return $uidary;
}



/*抢购时间存储方式转换*/
function transtime($datestr){
    $cutstr = explode(':',$datestr);
    $str_hour = trim($cutstr[0]);
    $str_hour = intval($str_hour)*3600;
    $str_mintu= trim($cutstr[1]);
    $str_mintu= intval($str_mintu)*60;
    $transtime= ($str_hour+$str_mintu);
    return $transtime;
}
function transdate($inttime){
    $inttime = trim($inttime);
    $day_num = $inttime%3600;
    $minutenum = ($day_num/60);
    if($minutenum<10){
        $minutenum = "0$minutenum";
    }
    $day_num  = intval($inttime/3600);
    if($day_num<10){
        $day_num = "0$day_num";
    }
    echo $day_num.':'.$minutenum;
}

/**
 * 去除代码中的空白和注释
 * @param string $content 代码内容
 * @return string
 */
function strip_whitespace($content) {
    $stripStr   = '';
    //分析php源码
    $tokens     = token_get_all($content);
    $last_space = false;
    for ($i = 0, $j = count($tokens); $i < $j; $i++) {
        if (is_string($tokens[$i])) {
            $last_space = false;
            $stripStr  .= $tokens[$i];
        } else {
            switch ($tokens[$i][0]) {
                //过滤各种PHP注释
                case T_COMMENT:
                case T_DOC_COMMENT:
                    break;
                //过滤空格
                case T_WHITESPACE:
                    if (!$last_space) {
                        $stripStr  .= ' ';
                        $last_space = true;
                    }
                    break;
                case T_START_HEREDOC:
                    $stripStr .= "<<<THINK\n";
                    break;
                case T_END_HEREDOC:
                    $stripStr .= "THINK;\n";
                    for($k = $i+1; $k < $j; $k++) {
                        if(is_string($tokens[$k]) && $tokens[$k] == ';') {
                            $i = $k;
                            break;
                        } else if($tokens[$k][0] == T_CLOSE_TAG) {
                            break;
                        }
                    }
                    break;
                default:
                    $last_space = false;
                    $stripStr  .= $tokens[$i][1];
            }
        }
    }
    return $stripStr;
}


/*根据用户名或真实姓名获取用户id*/
function get_uid($realnameorusername){
	$str = "username='".$realnameorusername."' or realname='".$realnameorusername."' or selfphone='".$realnameorusername."'";
	$id_str = db('user')->where($str)->field('id')->select();
    $new_id = [];
    if(is_array($id_str)){
		foreach($id_str as $v){
			$new_id[]=$v['id'];
		}
		//return implode(',',$new_id);
    }
    return $new_id;
}

/*SCB操作日志  xuanfeng  20200803*/
function mybot_his($uid,$isadd,$nums,$fromid,$info=''){
    $data['uid'] = intval($uid);
    $data['isadd']= $isadd;
    $data['nums'] = $nums;
    $data['fromuid'] = $fromid;
    $data['ctime']   = time();
    $data['info']    = $info;
    return db('mybot')->insert($data);
}

/*共享豆操作日志  xuanfeng  20190620*/
function points_his($uid,$isadd,$nums,$fromid,$info=''){
	$data['uid'] = intval($uid);
	$data['isadd']= $isadd;
	$data['nums'] = $nums;
	$data['fromuid'] = $fromid;
	$data['ctime']	 = time();
	$data['info']	 = $info;
	return db('points')->insert($data);
}
/*atc操作日志,现在名字叫做团队奖*/
function wages_his($uid,$isadd,$nums,$fromid,$info=''){
	$data['uid'] = intval($uid);
	$data['isadd']= $isadd;
	$data['nums'] = $nums;
	$data['fromuid'] = $fromid;
	$data['ctime']	 = time();
	$data['info']	 = $info;
	return db('wages')->insert($data);
}
/*直推奖励操作日志*/
function pushs_his($uid,$isadd,$nums,$fromid,$info=''){
	$data['uid'] = intval($uid);
	$data['isadd']= $isadd;
	$data['nums'] = $nums;
	$data['fromuid'] = $fromid;
	$data['ctime']	 = time();
	$data['info']	 = $info;
	return db('pushslist')->insert($data);
}
/*根据用户Id 查看接收会员的用户名*/
function userallinfo($uid){
	if(empty($uid)){
		return [];
	}
	$uname = db('user')->where("id='".$uid."'")->find();
    if(!empty($uname)){
        $cardinfo = db("card_apply")->where("user_id", "=", $uname['id'])->where('status', 1)->find();
        if(!empty($cardinfo)){
            $uname['selfcard'] = $cardinfo['selfcard'];
            if(empty($uname['realname'])){
                $uname['realname'] = $cardinfo['realname'];
            }
            $uname['mustman'] = $cardinfo['mustman'];
        }
    }

	return empty($uname)?[]:$uname;
}

/*本金和天数以及百分比进来，获取一共多少利息，本金和利息分别是多少*/
function countprofit($price,$day,$percent){
    $profit = ($price*$percent/100);
    $profit = round($profit,2);
    $profit_day = ($profit/$day);
    $profit_day = round($profit_day,2);
    $can_have = ($price+$profit);
	//应收费用要整数！！！
    $can_have = round($can_have,0);
    return ['profitall'=>$profit,'profitday'=>$profit_day,'profit_and_day'=>$can_have];
}
/*获取buyid这一单的全部信息*/
function buyidorder($peiduiid){
	$list = db(config('db_order_table'))->where("peiduiid='".$peiduiid."'")->select();

  if(empty($list[0])){
    $ckorder = db(config('db_order_table'))->find();
    $newck   = [];
    foreach($ckorder as $k=>$v){
      $newck[$k] = '';
    }
    return $newck;
  }

	if(count($list)<=1){
		return $list[0];
	}else{
		$buyuidatc  = [];
		$caifen     = [];
		$price      = [];
		$dayaddprice= [];
		$basicprice = [];
		foreach($list as $k=>$v){
			$buyuidatc[] = $v['buyuidatc'];
			$caifen[] = $v['caifen'];
			$title = str_replace('[拆分]','',$v['title']);
			$price[] = $v['price'];
			$dayaddprice[] = $v['dayaddprice'];
			$basicprice[] = $v['basicprice'];
		}
		$info = $list[0];
		$info['buyuidatc']  = array_sum($buyuidatc);
		$info['caifen']     = array_sum($caifen);
		$info['title']      = $title;
		$info['price']      = array_sum($price);
		$info['dayaddprice']= array_sum($dayaddprice);
		$info['basicprice'] = array_sum($basicprice);
		return $info;
	}
}
/*确认收到款项，系统自动调用*/
function sureget($id,$orderinfo=''){
	/*如果没有传过来订单信息，那就直接读取订单信息*/
	$orderinfo = db(config('db_order_table'))->where("id='".$id."' and paystatus=1")->find();

	$data['paystatus'] = 2;
	$s = db(config('db_order_table'))->where("id='".$id."'")->update($data);
	if($s){
    //让对应的那个订单可以出售--xuanfeng--2020-03-15
    $dataxs['xs'] = 2;
    db(config('db_order_table'))->where("id='".$orderinfo['match_oid']."'")->update($dataxs);

		/*发放各方的奖金，先发放三级分销的*/
		$price_basic = $orderinfo['dayaddprice'];
		/*是否有一级上级*/
		$thisuser = userallinfo($orderinfo['buyuid']);

		//查出本人的所有上级（不包含自己），按照一级
		//论功行赏，如果levelid=2,奖励$price_basic的1%   如果是3 奖励 2%    如果是3 奖励3%  如果是1 自动忽略团队奖
		$user_upary = excommend($thisuser['recommend']);
		$is_send_money = array();
		if(!empty($user_upary)){
			$reverse_up = array_reverse($user_upary);
			foreach($reverse_up as $v){
				if($v==$thisuser['id']){
					continue;
				}
				/*查询这个人是什么等级，如果是1级就不发*/
				$my_level = db('user')->where("id='".$v."'")->field('id,levelid')->find();
				if($my_level['levelid']>1){
					if(in_array($my_level['levelid'],$is_send_money)){
						continue;//如果该级别发了，那就不继续发了
					}
					if($my_level['levelid']==2){
						$can_have_price = round(($orderinfo['dayaddprice']*0.01),2);
					}
					if($my_level['levelid']==3){
						$can_have_price = round(($orderinfo['dayaddprice']*0.03),2);
					}
					if($my_level['levelid']==4){
						$can_have_price = round(($orderinfo['dayaddprice']*0.06),2);
					}
					$is_send_money[] = $my_level['levelid'];
					//开始发奖，记录下来发奖的历史就行了
					//发放奖金，平级不拿团队奖
					db('user')->where("id='".$v."'")->setInc('wagesall',$can_have_price);
//                    wages_his($v,1,$can_have_price,0,'团队奖[下级'.$thisuser['username'].'订单成交]');
                    wages_his($v,1,$can_have_price,0,'团队奖[下级订单成交]');
				}
			}
		}
		return 1;//确认收款成功！
	}else{
		return 2;//有bug!!!
	}
}

//打印数组
function print_pre($list){
	echo '<pre>';
	print_r($list);die();
}

function remove_tag($str){
    $search = ['<', '>', '\"', '\'', '~', '!', '@', '#', '$', '%', '^', '*', '|', '?'];
    $res = ['','','','','','','','','','','','','',''];
    return str_replace($search, $res, $str);
}
//过滤防止非法提交数据
function cut_not_acccept($data,$type=1){
  //1.去除空格  2.不去掉空格
  $data = str_replace('//','',$data);

  $data = strip_tags($data);
  if($type==1){
    $data  = str_replace(' ','',$data);
  }
  return $data;
}


function transdate3($inttime){
    $inttime = trim($inttime);
    $day_num = $inttime%3600;
    $minutenum = ($day_num/60);
    if($minutenum<10){
        $minutenum = "0$minutenum";
    }
    $day_num  = intval($inttime/3600);
    if($day_num<10){
        $day_num = "0$day_num";
    }
    return $day_num.':'.$minutenum;
}
/*查看产品名称*/
function get_goodsname($good_id){
	$title = db('goods')->where("id='".$good_id."'")->find();
	return empty($title)?'':$title['title']."(".transdate3($title['time_start'])."--".transdate3($title['time_end']).")";
}

function match_chinese($chars,$encoding='utf8')
{
    $pattern ='/[\x{4e00}-\x{9fa5}0-9]/u';
    preg_match_all($pattern,$chars,$result);
    $temp =join('',$result[0]);
    return $temp==$chars;
}

/**
 * 获取邀请码
 */
function getInviteCode(){
    $code = random(8);
    $u = db('user')->where("invite_code", $code)->find();
    if($u){
        return getInviteCode();
    }else{
        return $code;
    }
}

/**
 * 获取累计收入
 * @param $uid
 * @return bool|float|int|string|null
 */
function getProfits($uid){
    $profits1 = \db("orderearn")->where("uid", $uid)->where("status", 2)->where('isadd', 1)->sum('earnmoney');
    $profits2 = \db("pushslist")->where("uid", $uid)->where('isadd', 1)->sum('nums');
    return $profits1+$profits2;
}
/*获取某个用户的总资产*/
function user_pro_money($uid){
    //先读取我买的订单，还没有匹配的，并且计算出这些订单分别的收益
    $DB_TABDER = config('db_order_table');
    $order_all = \db($DB_TABDER)->where("buyuid='" . $uid . "' and peiduistatus=1")->field('id,price,basicprice')->select();
    $nowprice = 0;
    foreach ($order_all as $k => $v) {
        $nowprice = ($nowprice + $v['price']);
        $earn_now = \db('orderearn')->where("orderid='" . $v['id'] . "' and status=2")->sum('earnmoney');
        if ($earn_now > 0) {
            $nowprice = ($nowprice + $earn_now);
        }
    }
    return $nowprice;
}


/*这是，这是强制发放*/
//获取推荐人信息
function getParentInfo($user_id){
    $parent_id = db('user')->where('id', $user_id)->value('pid');
    if(empty($parent_id)){
        $user_name = '平台';
    }else{
        $user_name = db('user')->where('id', $parent_id)->value('username');
    }
    return $user_name;
}

/**
 * 分类等级
 * @return int
 */
function get_category_level(){
    return 2;
}

function getTemporary($user)
{
    $name = md5($user['id']);
    $data = \think\Cache::store('redis')->get($name);
    return $data;
}

function get_status_img($status){
    $arr = [
        '0'=>'/sucai/status0.png',//待付款
        '1'=>'/sucai/status1.png',//待发货
        '2'=>'/sucai/status2.png',//发货中
        '3'=>'/sucai/status3.png',//已完成
        '-1'=>'/sucai/status14.png',//已取消
    ];
    return $arr[$status];
}

function makeTemporary($user,$data){
    $name = md5($user['id']);
    \think\Cache::store('redis')->set($name,$data);
    return $name;
}